package com.atguigu.gulimall.authserver.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.authserver.constant.SmsConstant;
import com.atguigu.gulimall.authserver.feign.MemberFeign;
import com.atguigu.gulimall.authserver.feign.SmsFeign;
import com.atguigu.gulimall.authserver.vo.RegisterVo;
import com.atguigu.gulimall.authserver.vo.UserLoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class AuthController {
    @Autowired
    private SmsFeign smsFeign;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private MemberFeign memberFeign;

    @GetMapping("/reg.html")
    public String reg(){
        return "reg";
    }

    @GetMapping("/login.html")
    public String login(HttpSession session){
        Object attribute = session.getAttribute(SmsConstant.SPRING_SESSION_REDIS_KEY);
        if(attribute!=null){
            return "redirect:http://gulimall.com";
        }
        return "login";
    }



    @PostMapping("login")
    public String login(UserLoginVo userLoginVo, RedirectAttributes redirectAttributes, HttpSession session){
        R r = memberFeign.Login(userLoginVo);

        if(r.getCode()==0){
            com.atguigu.common.vo.MemberEntity memberEntity = r.getData("data", new TypeReference<com.atguigu.common.vo.MemberEntity>() {});
            session.setAttribute(SmsConstant.SPRING_SESSION_REDIS_KEY,memberEntity);
            return "redirect:http://gulimall.com";
        }

        String msg = r.getData("msg", new TypeReference<String>() {});
        Map<String, String> errors = new HashMap<>();
        errors.put("msg",msg);
        redirectAttributes.addFlashAttribute("errors",errors);
        return "redirect:http://auth.gulimall.com/login.html";
    }

    @GetMapping(value = "/sms/sendCode")
    @ResponseBody
    public R sendMessage(@RequestParam String phone){
        //TODO 接口防刷,大量请求访问短信请求
        //验证码校验，保证真实60s内发送一次请求
        String s = stringRedisTemplate.opsForValue().get(SmsConstant.REDIS_CODE_PRE_KEY + phone);
        if(!StringUtils.isEmpty(s)){
            s = s.split("_")[1];
            if(System.currentTimeMillis()-Long.parseLong(s)<60000){
                return R.error(BizCodeEnum.SEND_MESSAGE_ERROR.getCode(),BizCodeEnum.SEND_MESSAGE_ERROR.getMessage());
            }
        }
        Integer numCode = Integer.valueOf((Math.random() * 100000 + "").substring(0, 5));;
        stringRedisTemplate.opsForValue().set(SmsConstant.REDIS_CODE_PRE_KEY+phone,numCode+"_"+System.currentTimeMillis(),5, TimeUnit.MINUTES);
        smsFeign.sendMessage(phone,numCode);
        return R.ok();
    }

    @PostMapping("/register")
    public String register(@Valid RegisterVo registerVo, BindingResult bindingResult, RedirectAttributes redirectAttributes){
        if(bindingResult.hasErrors()){
            Map<String, String> errors = bindingResult.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }else {
            String s = stringRedisTemplate.opsForValue().get(SmsConstant.REDIS_CODE_PRE_KEY + registerVo.getPhone());
            if(!StringUtils.isEmpty(s)){
                if(registerVo.getCode().equals(s.split("_")[0])){
                    //使用过一次后，删除验证码，令牌机制
                    stringRedisTemplate.delete(SmsConstant.REDIS_CODE_PRE_KEY + registerVo.getPhone());
                    //进行登录
                    R r = memberFeign.register(registerVo);

                    if(r.getCode()==0){
                        return "redirect:http://auth.gulimall.com/login.html";
                    }else {
                        Map<String, String> errors = new HashMap<>();
                        String msg = r.getData("msg", new TypeReference<String>() {});
                        errors.put("msg",msg);
                        System.out.println(msg);
                        redirectAttributes.addFlashAttribute("errors",errors);
                        return "redirect:http://auth.gulimall.com/reg.html";
//                        if("手机号已经被注册".equals(msg)){
//                            errors.put("phone",msg);
//                            redirectAttributes.addFlashAttribute("errors",errors);
//                            return "redirect:http://auth.gulimall.com/reg.html";
//                        }else if(){
//
//                        }
                    }
                }else {
                    Map<String, String> errors = new HashMap<>();
                    System.out.println("验证码不正确");
                    errors.put("code","验证码不正确");
                    redirectAttributes.addFlashAttribute("errors",errors);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
            }else {
                Map<String, String> errors = new HashMap<>();
                errors.put("code","验证码过期，请重新发送");
                System.out.println("验证码过期，请重新发送");
                redirectAttributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        }
    }

}
